<template>
  <div>
    <v-card
      class="mx-auto pa-12 pb-8"
      elevation="8"
      max-width="1500"
      padding="0"
      rounded="lg"
    >
      <v-row>
        <!--左边-->
        <v-col>
          <v-img
            class="mx-auto my-6"
            max-width="228"
            src="@/assets/LOGO.png"
          ></v-img>
        </v-col>
        <!--右边-->
        <v-col>
          <v-card-title align="center">用户登录</v-card-title>
          <div class="text-subtitle-1 text-medium-emphasis">账号</div>

          <v-text-field
            v-model="name"
            :rules="[rules.required,rules.nameCounter]"
            density="compact"
            placeholder="请输入用户名"
            prepend-inner-icon="mdi-account-outline"
            variant="outlined"
          ></v-text-field>

          <div class="text-subtitle-1 text-medium-emphasis d-flex align-center justify-space-between">
            密码
            <!-- 忘记密码链接 -->
            <a
              class="text-caption text-decoration-none text-blue"
              rel="noopener noreferrer"
              @click="openForgotPasswordDialog"
            >
              忘记密码？
            </a>
          </div>

          <v-text-field
            v-model="password"
            :append-inner-icon="visible ? 'mdi-eye-off' : 'mdi-eye'"
            :rules="[rules.required, rules.pwdCounter]"
            :type="visible ? 'text' : 'password'"
            class="password-input"
            density="compact"
            placeholder="请输入密码"
            prepend-inner-icon="mdi-lock-outline"
            variant="outlined"
            @blur="blurInput($event)"
            @focus="focusInput"
          ></v-text-field>

          <v-card
            class="mb-12"
            color="surface-variant"
            variant="tonal"
          ></v-card>

          <!-- 登录按钮，跳转首页 -->
          <v-btn
            block
            class="mb-8"
            color="blue"
            size="large"
            variant="tonal"
            @click="login"
          >
            登录
          </v-btn>

          <v-card-text class="text-center">

          </v-card-text>
        </v-col>
      </v-row>
      <div class="card-bottom-images">
        <v-img :src="leftImage" class="left-image" max-height="100" max-width="100"></v-img>
        <v-img :src="rightImage" class="right-image" max-height="100" max-width="100"></v-img>
      </div>
    </v-card>


    <!--    忘记密码对话框-->
    <v-dialog v-model="forgotPasswordDialog" persistent>
      <v-container>
        <v-card class="mx-auto pa-12 pb-8" elevation="8" max-width="800" padding="0" rounded="lg" width="500">
          <v-card-title align="center">忘记密码</v-card-title>
          <!-- ... 其他内容 ... -->
          <div class="text-subtitle-1 text-medium-emphasis">账号</div>

          <v-text-field
            v-model="forgotPasswordName"
            :rules="[rules.required, rules.nameCounter]"
            density="compact"
            placeholder="请输入用户名"
            prepend-inner-icon="mdi-account-outline"
            variant="outlined"
          ></v-text-field>

          <div class="text-subtitle-1 text-medium-emphasis d-flex align-center justify-space-between">
            验证码
            <!--换取验证码按钮 -->

            <v-btn :disabled="countdown > 0" @click="getVerificationCode">获取验证码</v-btn>
          </div>

          <v-text-field
            v-model="verificationCode"
            density="compact"
            placeholder="请输入验证码"
            prepend-inner-icon="mdi-lock-outline"
            variant="outlined"
          ></v-text-field>

          <div class="text-subtitle-1 text-medium-emphasis">新密码</div>
          <v-text-field
            v-model="forgotPasswordPwd"
            :append-inner-icon="visible ? 'mdi-eye-off' : 'mdi-eye'"
            :rules="[rules.required, rules.pwdCounter]"
            :type="visible ? 'text' : 'password'"
            density="compact"
            placeholder="请设置新密码"
            prepend-inner-icon="mdi-lock-outline"
            variant="outlined"
            @click:append-inner="visible = !visible"
          ></v-text-field>

          <v-card-actions class="justify-center">
            <v-btn @click="closeForgotPasswordDialog">提交</v-btn>
          </v-card-actions>
        </v-card>
      </v-container>
    </v-dialog>


  </div>

</template>

<script lang="ts" setup>

import {ref} from "vue";
import {userStore} from "@/store/app";
import axios from "axios";

// 登录对话框中的信息
const user = userStore();
const name = ref('');
const password = ref('')

// 控制密码的显示
const visible = ref(false);

const leftImage = ref('https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/open_left.png');
const rightImage = ref('https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/open_right.png');

// 忘记密码输入框中的信息
const forgotPasswordName = ref(null);
const forgotPasswordPwd = ref(null);

const verificationCode = ref("");

//前端接收的验证码
const code = ref("");
const countdown = ref(0);

const getVerificationCode = () => {
  // 在这里执行获取验证码的逻辑
  // 例如发送请求给后端获取验证码
  axios.post("http://47.113.189.87:8080/users/sendCaptcha", {
    user_name: forgotPasswordName.value
  }).then(response => {
    if (response.data.code == 20001) {
      // 从服务器获取验证码
      code.value = response.data.data;

      // 模拟倒计时60秒
      countdown.value = 60;

      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value -= 1;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      // 处理获取验证码失败的情况
      console.error("获取验证码失败");
    }
  });

};

// 验证验证码是否正确
const validateVerificationCode = () => {
  return verificationCode.value === code.value;
};

// 忘记密码对话框打开与关闭
const forgotPasswordDialog = ref(false);

const openForgotPasswordDialog = () => {
  forgotPasswordDialog.value = true;
};

// 用于关闭对话框和更新密码
const closeForgotPasswordDialog = () => {
  forgotPasswordDialog.value = false;

  // 首先验证验证码是否正确
  if (!validateVerificationCode()) {
    alert('验证码错误，请重新输入');
    return;
  }

  // 执行修改密码的逻辑
  changePassword();

};

// 执行修改密码的逻辑
const changePassword = () => {
  // 在这里执行修改密码的逻辑
  // 例如发送请求给后端修改密码
  axios.post("http://47.113.189.87:8080/users/updatePassword", {
    user_name: forgotPasswordName.value,
    password: forgotPasswordPwd.value, // 这里使用忘记密码时用户输入的新密码
  }).then(response => {
    if (response.data.code === 20031) {
      // 密码修改成功逻辑
      console.log("密码修改成功");
      alert('密码修改成功');
    } else {
      // 密码修改失败逻辑
      console.error("密码修改失败");
      alert('密码修改失败');
    }
  });
};

// 输入框检验
const rules = {
  required: (value: string) => !!value || '此项为必填项',
  nameCounter: (value: string) => value.length >= 6 && value.length <= 12 || '用户名长度应在6到12位之间',
  pwdCounter: (value: string) => value.length >= 8 && value.length <= 12 || '密码长度应在8到12位之间',
  email: (value: string) => {
    const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return pattern.test(value) || '请输入正确邮箱格式'
  },
};

// 登录逻辑
const login = (message?: any) => {
  console.log('login')

  // 登录逻辑
  axios.post('http://47.113.189.87:8080/users/login', {
    name: name.value,
    password: password.value
  }).then((res) => {
    if (res.data.code === 20051) {
      // 登录成功逻辑
      console.log('登录成功', res.data.data)
      user.setUser(name.value, '@/assets/LOGO.png')
      user.changeLoginStatus(true);
      user.setLoginDialog(false)//这个代码是用于隐藏当前登录dialog的
    } else {
      // console.log(res.data.msg)
      alert(res.data.msg)
    }
  })
};


const focusInput = () => {
  if (!visible.value) {
    leftImage.value = 'https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/close_left.png';
    rightImage.value = 'https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/close_right.png';
  } else {
    leftImage.value = 'https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/open_left.png';
    rightImage.value = 'https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/open_right.png';
  }
  visible.value = !visible.value;
};

const blurInput = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (!target.classList.contains('password-input')) {
    leftImage.value = 'https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/open_left.png';
    rightImage.value = 'https://sakura-cjq.oss-rg-china-mainland.aliyuncs.com/open_close/open_right.png';
    visible.value = false;
  }
};

</script>
<style>
.card-bottom-images {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.left-image {
  margin-left: 0;
  margin-bottom: 0;
}

.right-image {
  margin-right: 0;
  margin-bottom: 0;
}

</style>
